package com.wxmit.starter.file.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.wxmit.base.constant.ShushanConstants;
import com.wxmit.starter.file.config.ShushanFileConfig;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 序列化
 * @author huangxiong
 * @date 2021/6/18
 */
public class FileRealmSerialize extends JsonSerializer<Object>  {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
       if(Objects.isNull(value)){
           gen.writeObject(value);
       }
        if (value instanceof String){
            gen.writeString(decorateFilePrefix((String)value));
        } else if (value instanceof Collection){
            Collection<String> list = (Collection<String>) value;
            List<String> newList = list.stream().map(it -> decorateFilePrefix(it)).collect(Collectors.toList());
            gen.writeObject(newList);
        }
    }
    @Override
    public void serializeWithType(Object value, JsonGenerator g, SerializerProvider provider,
                                  TypeSerializer typeSer) throws IOException
    {
        // NOTE: need not really be string; just indicates "scalar of some kind"
        WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
                typeSer.typeId(value, JsonToken.VALUE_STRING));
        serialize(value, g, provider);
        typeSer.writeTypeSuffix(g, typeIdDef);
    }

    private final static String HTTPS_PREFIX = "https:/";
    private final static String HTTP_PREFIX = "http:/";


    public String decorateFilePrefix(String val){
        if(Objects.nonNull(val) && !val.startsWith(HTTP_PREFIX) && !val.startsWith(HTTPS_PREFIX)){
            return ShushanFileConfig.fileRealm + ShushanFileConfig.urlPrefix + val;
        }
        return val;
    }

}
